﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using nwrole.lib;

namespace nwrole.lib2 {
    public class TcpChannel<T> : IDisposable {

        public T Channel { get; private set; }

        public TcpChannel(string url) {
            Connect(url, null, null);
        }

        public TcpChannel(string url, string username, string password) {
            Connect(url, username, password);
        }

        private void Connect(string url, string username, string password) {
            //try {
                EndpointAddress address = new EndpointAddress("net.tcp://" + url);
                NetTcpBinding binding = new NetTcpBinding();
                binding.ReceiveTimeout = new TimeSpan(0, 0, 120);
                binding.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max;
                binding.MaxReceivedMessageSize = 2147483647;
                binding.MaxConnections = 100;
                ChannelFactory<T> factory = new ChannelFactory<T>(binding, address);
                if(!string.IsNullOrEmpty(username)) {
                    factory.Credentials.Windows.ClientCredential.UserName = username;
                    factory.Credentials.Windows.ClientCredential.Password = password;
                }
                else
                    factory.Credentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
                
                Channel = factory.CreateChannel();

            /*} catch (Exception exception) {
                EventLogger.LogException("TcpChannel exception: ", exception);
            }*/
        }

        public void Dispose() {
            try {
                ((IClientChannel)Channel).Close(TimeSpan.FromSeconds(30));
                ((IClientChannel)Channel).Dispose();
            } catch (Exception exception) {
                EventLogger.LogException("TcpChannel.Dispose", exception);
            }
        }

    }
}
